package com.itheima.dao;

import com.itheima.domain.Student;
import com.itheima.utils.DataSourceUtils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class StudentDaoimpl implements StudentDao{
    @Override
    public int add(Student student) {
        //1，获取连接
        Connection connection = DataSourceUtils.getConnection();
        //2，定义sql
        String sql="INSERT INTO student VALUES(null,?,?)";
        //3，获取执行对象
        PreparedStatement pre=null;
        //4，设置占位符
        int i=0;
        try {
            pre= connection.prepareStatement(sql);
            pre.setString(1,student.getName());
            pre.setInt(2,student.getAge());
           //5.执行sql
            i = pre.executeUpdate();

        } catch (Exception e) {
            e.printStackTrace();
        }finally {

        }
        //6，释放资源
        DataSourceUtils.close(connection,pre);
        return i;







    }

    @Override
    public int update(Student student) {
        Connection connection = DataSourceUtils.getConnection();

        String sql="UPDATE student SET name=? , age=? WHERE id=?";

        PreparedStatement pre=null;
        int i =0;
        try {
            pre= connection.prepareStatement(sql);
            pre.setString(1,student.getName());
            pre.setInt(2,student.getAge());
            pre.setInt(3,student.getId());

            i= pre.executeUpdate();


        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DataSourceUtils.close(connection,pre);

        }
        return i;


    }

    @Override
    public int deleteByid(int id) {
        Connection connection = DataSourceUtils.getConnection();
        String sql="DELETE FROM student WHERE id=?";
        PreparedStatement prep =null;
        int i =0;
        try {
         prep=    connection.prepareStatement(sql);
         prep.setInt(1,id);
           i=  prep.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            DataSourceUtils.close(connection,prep);

        }


        return i;
    }

    @Override
    public Student findByid(int id) {
        Connection connection = DataSourceUtils.getConnection();
        String sql="SELECT * FROM student WHERE id=?";

        PreparedStatement prep =null;
        try {
            prep= connection.prepareStatement(sql);
            prep.setInt(1,id);
            ResultSet resultSet = prep.executeQuery();


        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }


        return null;
    }

    @Override
    public List<Student> findAll() {
        return null;
    }
}
